package com.sky.service.impl;


import com.alibaba.fastjson.JSON;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersRejectionDTO;
import com.sky.entity.Orders;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.OrdersMapper;
import com.sky.service.OrdersService;
import com.sky.utils.WeChatPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServerImpl webSocketServer;

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void refuse(OrdersRejectionDTO ordersRejectionDTO) {
        Orders ordersinfo = ordersMapper.getById(ordersRejectionDTO.getId());
        if (ordersinfo.getStatus()!=Orders.TO_BE_CONFIRMED){
            throw  new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //用户退款
        try {
            weChatPayUtil.refund(ordersinfo.getNumber(),ordersinfo.getNumber(),ordersinfo.getAmount(),ordersinfo.getAmount());
        } catch (Exception e) {
         throw  new OrderBusinessException("退款失败");
        }
        //组装订单信息
        Orders orders = Orders.builder()
                .id(ordersRejectionDTO.getId())
                .status(Orders.CANCELLED)
                .payStatus(Orders.REFUND)
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .build();
        ordersMapper.update(orders);

    }

    /**
     * 微信支付成功
     * @param outTradeNo
     */
    @Override
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);

        //1、使用websocket向浏览器发送来单提醒
        Map map = new HashMap();
        map.put("type",1); //1：来单提醒   2：催单提醒
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号：" + outTradeNo);
        final String msg = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(msg);

    }
}
